package com.linkage.jz.bankruptcy.activity.Person;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.base.BaseWhiteActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * A login screen that offers login via email/password.
 */
public class PersonSettingPhoneActivity extends BaseWhiteActivity implements OnClickListener {
    private static final String TAG = PersonSettingPhoneActivity.class.getSimpleName();

    private ShapeLoadingDialog shapeLoadingDialog;

    TextView btn_save, getnphonecode, getophonecode;
    EditText et_newphonevcode, et_ophonevcode, et_oldphone, et_newphone;


    private  static String mPhone;
    public static void start(Context context,String phone) {
        mPhone = phone;
        Intent intent = new Intent(context, PersonSettingPhoneActivity.class);
        context.startActivity(intent);
    }

    private PublicNoticeDialog noticeDialog;

    private int dialogflag = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_setting_setphone, "修改手机号");
        initview();
        shapeLoadingDialog = new ShapeLoadingDialog(this);

        dialogflag = 1;
        noticeDialog = new PublicNoticeDialog(PersonSettingPhoneActivity.this,onClickListener,
                1,"提示","债权人会议表决规则如下: 一、适用范围 本议事机制及表决规则使用的范围包括表决债务人财产管理方 案、破产变价方案、破产财产分配方案等法律规定的表，一、适用范围 本议事机制及表决规则使用的范围包括表决债务人财产管理方 案、破产变价方案、破产财产分配方案等法律规定的表一、适用范围 本议事机制及表决规则使用的范围包括表决债务人财产管理方 案、破产变价方案、破产财产分配方案等法律规定的表一、适用范围 本议事机制及表决规则使用的范围包括表决债务人财产管理方 案、破产变价方案、破产财产分配方案等法律规定的表",
                "不同意","同意");
        noticeDialog.show();

        shapeLoadingDialog = new ShapeLoadingDialog(this);
    }


    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.ll_close:
                    noticeDialog.dismiss();
                    if(dialogflag==1) {
//                        SPUtils.getInstance(Consts.SPNAME).put("userToken", "");
//                BankruptcyApp.loginInfo = null;
//                        BankruptcyApp.userToken = "";
//                        BankruptcyApp.loginInfo = null;
//                        SPUtils.getInstance(Consts.SPNAME).put("loginUser", "");
//                        SPUtils.getInstance(Consts.SPNAME).put("loginPwd", "");
//                        finish();
                        finish();
                    }
                    break;

                case R.id.btn_chancel_notice:
//                   Boolean flag =  noticelxDialog.cb_agree.isChecked();
                    noticeDialog.dismiss();
                    if(dialogflag ==1) {
                        finish();
                    }

                    break;

                case R.id.btn_save_notice:

                    if(dialogflag ==1)
                    {

                    }
                    noticeDialog.dismiss();
                    break;

            }
        }
    };

    //初始化视图
    private void initview() {
        //登录层、下拉层、其它登录方式层
        btn_save = findViewById(R.id.btn_save);
        getnphonecode = findViewById(R.id.getnphonecode);
        getophonecode = findViewById(R.id.getophonecode);
        et_newphonevcode = findViewById(R.id.et_nphonevcode);
        et_ophonevcode = findViewById(R.id.et_ophonevcode);
        et_oldphone = findViewById(R.id.et_oldphone);
        et_oldphone.setText(mPhone);
        et_newphone = findViewById(R.id.et_newphone);

        btn_save.setOnClickListener(this);
        getnphonecode.setOnClickListener(this);
        getophonecode.setOnClickListener(this);

        et_newphone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showCode1();
                showCode2();
                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        et_oldphone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showCode1();
                showCode2();
                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });


        et_ophonevcode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showCode1();
                showCode2();
                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        et_newphonevcode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showCode1();
                showCode2();
                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        showCode1();
        showCode2();
        showSave();
    }

    private void showCode1()
    {
        String str1 =  et_oldphone.getText().toString().trim();
        if(str1.equalsIgnoreCase(""))
        {
            getophonecode.setClickable(false);
            getophonecode.setTextColor(getResources().getColor(R.color.btnosel));
        }else{
            getophonecode.setClickable(true);
            getophonecode.setTextColor(getResources().getColor(R.color.btsel));
        }
    }

    private void showCode2()
    {
        String str1 =  et_oldphone.getText().toString().trim();
        String str2 =  et_ophonevcode.getText().toString().trim();
        String str3 =  et_newphone.getText().toString().trim();

        if(!str1.equalsIgnoreCase("") && !str2.equalsIgnoreCase("")
         && !str3.equalsIgnoreCase(""))
        {
            getnphonecode.setClickable(true);
            getnphonecode.setTextColor(getResources().getColor(R.color.btsel));

        }else{
            getnphonecode.setClickable(false);
            getnphonecode.setTextColor(getResources().getColor(R.color.btnosel));
        }
    }

    private void showSave()
    {
        String str1 =  et_oldphone.getText().toString().trim();
        String str2 =  et_ophonevcode.getText().toString().trim();
        String str3 =  et_newphone.getText().toString().trim();
        String str4 =  et_newphonevcode.getText().toString().trim();


        if(!str1.equalsIgnoreCase("") && !str2.equalsIgnoreCase("")
                && !str3.equalsIgnoreCase("")&& !str4.equalsIgnoreCase(""))
        {

            btn_save.setClickable(true);
            btn_save.setBackgroundResource((R.drawable.login_corner_btn));
        }else{
            btn_save.setClickable(false);
            btn_save.setBackgroundResource((R.drawable.login_corner_nosel_btn));
        }


    }

    @Override
    public void onClick(View view) {
        String oldphone = "";
        String newphone = "";
        String newcode = "";
        String oldcode = "";
        switch (view.getId()) {
            case R.id.getnphonecode:
                newphone = et_newphone.getText().toString();
//                oldphone = et_oldphone.getText().toString();
                oldphone = et_oldphone.getText().toString();
                if ("".equalsIgnoreCase(oldphone)) {
                    showToast("原手机号不能为空");
                    return;
                }
                oldcode = et_ophonevcode.getText().toString();
                if ("".equalsIgnoreCase(oldcode)) {
                    showToast("原手机验证码不能为空");
                    return;
                }

                if ("".equalsIgnoreCase(newphone)) {
                    showToast("新手机号不能为空");
                    return;
                }

                getSMSCode2(oldphone,oldcode,newphone);
//                getSMSCode(newphone,"1");
                break;
            case R.id.getophonecode:
                oldphone = et_oldphone.getText().toString();
                if ("".equalsIgnoreCase(oldphone)) {
                    showToast("原手机号不能为空");
                    return;
                }
//                MyCountDownTimer countDownTimer1 = new MyCountDownTimer(1, 60000, 1000);
//                countDownTimer1.start();
                getSMSCode(oldphone,4);
//                getSMSCode(oldphone,"1");
                break;
            case R.id.btn_save:
                oldphone = et_oldphone.getText().toString();
                if ("".equalsIgnoreCase(oldphone)) {
                    showToast("原手机号不能为空");
                    return;
                }
                oldcode = et_ophonevcode.getText().toString();
                if ("".equalsIgnoreCase(oldcode)) {
                    showToast("原手机验证码不能为空");
                    return;
                }

                newphone = et_newphone.getText().toString();
                if ("".equalsIgnoreCase(newphone)) {
                    showToast("新手机号不能为空");
                    return;
                }
                newcode = et_newphonevcode.getText().toString();
                if ("".equalsIgnoreCase(newcode)) {
                    showToast("新手机验证码不能为空");
                    return;
                }


                SaveData(oldphone, newphone, newcode, oldcode);
                break;
            case R.id.icon_back:
                finish();


                break;

            default:
                break;
        }
    }

    public void getSMSCode(String mobile,final int source) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        showProgress();


        Observable<JsonObject> observable  ;

        observable = Network
                .getAPIService()
                .getSMSCode(mobile,source);


        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideProgress();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {

                            super.onNext(json);
                            return;
                        }

                            MyCountDownTimer countDownTimer2 = new MyCountDownTimer(1,60000, 1000);
                            countDownTimer2.start();


                        showToast("提交成功"+json.get("data"));
//                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        super.onError(e);
                    }
                });

    }

    public void getSMSCode2(String preNumber,final String preCaptcha,String newNumber) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        showProgress();


        Observable<JsonObject> observable  ;
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        observable = Network
                .getAPIService()
                .getSMSCode2(userToken,preNumber,preCaptcha,newNumber);


        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideProgress();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {

                            super.onNext(json);
                            return;
                        }


                            MyCountDownTimer countDownTimer2 = new MyCountDownTimer(2,60000, 1000);
                            countDownTimer2.start();


                        showToast("提交成功"+json.get("data"));
//                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        super.onError(e);
                    }
                });

    }


    public void SaveData(String oldphone, final String newphone, String newcode, String oldcode) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.APPID)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("avatar", "")
                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("token", "")
                .add("userId", userId)
                .add("userToken", userToken)
                .add("newNumber", newphone)
                .add("newCaptcha", newcode)
                .build();

        String url = Consts.WEBURL_MODIFYPHONE;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(PersonSettingPhoneActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                showToast("提交成功");
                                SPUtils.getInstance(Consts.SPNAME).put("userToken", "");
//                BankruptcyApp.loginInfo = null;
                                BankruptcyApp.userToken = "";
                                BankruptcyApp.loginInfo = null;
                                SPUtils.getInstance(Consts.SPNAME).put("loginUser", "");
                                SPUtils.getInstance(Consts.SPNAME).put("loginPwd", "");
                                SPUtils.getInstance(Consts.SPNAME).put("setPhone", "1");
                                finish();
//                                Toast.makeText(PersonSettingPhoneActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
//                                BankruptcyApp.loginInfo.setMobile(newphone);

                            }

                        });
                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
//                                Toast.makeText(PersonSettingPhoneActivity.this, "保存失败："+object.optString("msg"), Toast.LENGTH_SHORT).show();
                                showToast("提交失败："+object.optString("msg"));
                            }

                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(PersonSettingPhoneActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

    private class MyCountDownTimer extends CountDownTimer {

        private int num = 0;

        public MyCountDownTimer(int num, long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            this.num = num;
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            if (num == 1) {
                getophonecode.setClickable(false);
                getophonecode.setText(l / 1000 + "秒");
            } else if (num == 2) {
                getnphonecode.setClickable(false);
                getnphonecode.setText(l / 1000 + "秒");
            }

        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            if (num == 1) {
                getophonecode.setText("重新获取");
                //设置可点击
                getophonecode.setClickable(true);
            } else if (num == 2) {
                getnphonecode.setText("重新获取");
                //设置可点击
                getnphonecode.setClickable(true);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            exit();
//            return false;

            if(noticeDialog.isShowing())
            {
                return  true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }



}

